package com.wangyk.gateway.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_DECORATION_FILTER_ORDER;
import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_TYPE;

/**
 * gateway的过滤器
 */
@Component
public class TokenFilter extends ZuulFilter
{
    /**
     * 设置过滤器的类型
     */
    public String filterType()
    {
        return PRE_TYPE;
    }

    /**
     * 设置过滤器的顺序，数字越小优先级越高
     */
    public int filterOrder()
    {
        return PRE_DECORATION_FILTER_ORDER - 1;
    }

    public boolean shouldFilter()
    {
        return true;
    }

    /**
     * 填写业务逻辑
     */
    public Object run()
        throws ZuulException
    {
        /**
         * 获取当前请求的上下文
         * */
        RequestContext currentContext = RequestContext.getCurrentContext();
        /**
         * 从上下文中获取请求
         * */
        HttpServletRequest request = currentContext.getRequest();
        /**
         * 可以从url中获取，或者是cookies或者是header中获取参数
         * */
        String token = request.getParameter("token");
        String openid = request.getParameter("openId");
        /**
         * 如果没有权限
         * */
        if (StringUtils.isEmpty(token)&&StringUtils.isEmpty(openid))
        {
            //表示为不通过
            currentContext.setSendZuulResponse(false);
            //设置Http的返回码
            currentContext.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value());
        }
        return null;
    }
}
